package com.zhengshang.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.WriterException;
import com.zhengshang.api.domain.*;
import com.zhengshang.api.service.*;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.constant.UserConstants;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysDictData;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.core.page.TableDataInfo;
import com.zhengshang.common.oss.OssUtils;
import com.zhengshang.common.utils.*;
import com.zhengshang.common.utils.uuid.IdUtils;
import com.zhengshang.security.service.SmsService;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysDictTypeService;
import com.zhengshang.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @author HY
 * @version 1.0.0
 * @ClassName LoginController.java
 * @Description TODO
 * @createTime 2020年12月03日 10:09
 */
@Api(tags = "用户模块")
@RequestMapping("/user")
@RestController
public class UserController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private IAppBrowseRecordService appBrowseRecordService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppCashingRecordService appCashingRecordService;
    @Autowired
    private IAppActivityService appActivityService;
    @Autowired
    private IAppBalanceRecordService appBalanceRecordService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private IAppBankService appBankService;

    @ApiOperation(value = "用户是否有优惠券")
    @PostMapping("/isHaveCoupon")
    public AjaxResult userIsHaveCoupon(HttpServletRequest request) {
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        SysUser appUser = loginAppUser.getAppUser();
        Long userId = appUser.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        Integer couponCount = sysUser.getCouponCount();
        if (com.zhengshang.common.utils.StringUtils.isNull(couponCount)) {
            couponCount = 0;
        }
        Boolean isHaveCoupon = couponCount > 0;
        return AjaxResult.success(isHaveCoupon);
    }

    @ApiOperation(value = "获取个人信息")
    @PostMapping("/getUserInfo")
    public AjaxResult getUserInfo(
            HttpServletRequest request, HttpServletResponse response) {

        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        //获取数据库最新数据并更新到redis中
        loginAppUser.setAppUser(userService.selectUserById(loginAppUser.getAppUser().getUserId()));
        if (StringUtils.isNotBlank(loginAppUser.getAppUser().getAvatar()) && loginAppUser.getAppUser().getAvatar().indexOf("https://") == -1) {
            loginAppUser.getAppUser().setAvatar(configService.selectConfigByKey("sys.oss.file.header") + loginAppUser.getAppUser().getAvatar());
        }
        SysUser user = new SysUser();
        user.setUserType(UserConstants.USER_TYPE_APP);
        user.setUpUserId(loginAppUser.getAppUser().getUserId());
        user.setUpUpUserId(loginAppUser.getAppUser().getUserId());
        loginAppUser.getAppUser().setTeamNum(userService.queryMyTeamNum(user));
        loginAppUser.getAppUser().setPartnerLevel(PartnerLevelUtils.getLevel(loginAppUser.getAppUser().getContributionValue()));
        tokenService.refreshToken(loginAppUser);
        return AjaxResult.success(loginAppUser.getAppUser());
    }

    /**
     * 查询用户收益记录列表
     */
    @GetMapping("/balanceLogList")
    public TableDataInfo balanceLogList(
            HttpServletRequest request,AppBalanceRecord appBalanceRecord)
    {
        startPage();
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        appBalanceRecord.setUserId(loginAppUser.getAppUser().getUserId());
        List<AppBalanceRecord> list = appBalanceRecordService.selectAppBalanceRecordList(appBalanceRecord);
        return getDataTable(list);
    }

    /**
     * @throws
     * @title 修改用户信息
     * @description
     * @author admin
     * @updateTime 2021/3/4 17:09
     */
    @ApiOperation(value = "修改用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickName", value = "用户昵称", dataType = "String", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(
            @RequestParam String nickName,
            HttpServletRequest request, HttpServletResponse response) {

        try {
            if (StringUtils.isBlank(nickName)) {
                return AjaxResult.error("参数异常");
            }
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            loginAppUser.getAppUser().setNickName(nickName);
            userService.updateUserNickName(loginAppUser.getAppUser());
            tokenService.refreshToken(loginAppUser);
            logger.info("用户<" + loginAppUser.getUsername() + ">信息修改成功");
            return AjaxResult.success("修改信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("修改信息失败，请稍后再试或联系管理员");
        }
    }

    /**
     * @throws
     * @title 修改头像
     * @description
     * @author admin
     * @updateTime 2021/3/4 17:09
     */
    @ApiOperation(value = "修改头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "avatarBase64", value = "用户头像Base64字符串(不进行处理，需包含\"data:image/png;base64,\"等信息)", dataType = "String", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/updateAvatar")
    public AjaxResult updateAvatar(
            @RequestBody String avatarBase64,
            HttpServletRequest request, HttpServletResponse response) throws IOException {

        String base64 = "";
        String dataPrix = "";
        if (StringUtils.isBlank(avatarBase64) || avatarBase64.indexOf("data:") != 0) {
            return AjaxResult.error("上传文件格式不正确");
        } else {
            String[] d = avatarBase64.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                base64 = d[1];
            } else {
                return AjaxResult.error("上传数据不合法");
            }
        }
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//base64编码的png图片数据
            suffix = ".png";
        } else {
            return AjaxResult.error("上传图片格式不正确");
        }
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(ServletUtils.getRequest());
            JSONObject object = OssUtils.uploadFile(base64, OssUtils.FILE_TYPE_AVATAR, IdUtils.simpleUUID() + suffix);
            if (object == null) {
                return AjaxResult.error("oss上传失败");
            }
            String avatar = object.getString("objectID");
            if (userService.updateUserAvatar(loginAppUser.getUsername(), avatar)) {
                // 更新缓存用户头像
                loginAppUser.getAppUser().setAvatar(avatar);
                tokenService.setLoginAppUser(loginAppUser);
                return AjaxResult.success("更新成功", configService.selectConfigByKey("sys.oss.file.header") + avatar);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error(MessageUtils.message("user.avatar.upload.error"));
    }

    /**
     * @throws
     * @title 修改密码
     * @description
     * @author admin
     * @updateTime 2020/12/7 17:58
     */
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "旧密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "newPassword", value = "新密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "confirmPassword", value = "确认密码", dataType = "String", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(
            @RequestParam String oldPassword,
            @RequestParam String newPassword,
            @RequestParam String confirmPassword,
            HttpServletRequest request, HttpServletResponse response) {

        try {
            if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(confirmPassword)) {
                return AjaxResult.error("参数异常");
            }
            if (!newPassword.equals(confirmPassword)) {
                return AjaxResult.error("两次密码不一致！");
            }
            if (newPassword.equals(oldPassword)) {
                return AjaxResult.error("新密码不能与旧密码一致！");
            }

            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            if (!SecurityUtils.matchesPassword(oldPassword, loginAppUser.getPassword())) {
                return AjaxResult.error("原密码不正确！");
            }
            String newPwd = SecurityUtils.encryptPassword(newPassword);
            loginAppUser.getAppUser().setPassword(newPwd);
            userService.resetUserPwd(loginAppUser.getUsername(), loginAppUser.getPassword());
            tokenService.refreshToken(loginAppUser);
            logger.info("用户<" + loginAppUser.getUsername() + ">密码修改成功");

            //TODO 发送消息通知(1系统通知，2短信通知)
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("密码修改失败，请稍后再试或联系管理员");
        }
    }

    /**
     * @throws
     * @title 我的团队列表
     * @description
     * @author admin
     * @updateTime 2021/3/5 14:03
     */
    @PreAuthorize("@ss.hasPermi('app:user:teamList')")
    @ApiOperation(value = "我的团队列表")
    @PostMapping("/teamList")
    public AjaxResult teamList(
            HttpServletRequest request, HttpServletResponse response) {

        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            SysUser sysUser = new SysUser();
            sysUser.setUserType(UserConstants.USER_TYPE_APP);
            sysUser.setUpUserId(loginAppUser.getAppUser().getUserId());
            sysUser.setUpUpUserId(loginAppUser.getAppUser().getUserId());
            List<SysUser> userList = userService.queryMyTeam(sysUser);

            logger.info("获取我的团队列表成功");
            return AjaxResult.success(userList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取我的团队列表失败，请稍后再试或联系管理员");
        }
    }

    /**
     * 获取浏览记录列表
     */
    @PreAuthorize("@ss.hasPermi('app:user:browse')")
    @ApiOperation(value = "获取浏览记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = false, dataType = "int", paramType = "query")
    })
    @GetMapping("/browseList")
    public AjaxResult browseList(
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) {
        if (pageNum == null || pageNum.intValue() <= 0) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        AppBrowseRecord appBrowseRecord = new AppBrowseRecord();
        appBrowseRecord.getParams().put("pageNum", pageNum);
        appBrowseRecord.getParams().put("pageSize", pageSize);
        appBrowseRecord.setUserId(loginAppUser.getAppUser().getUserId());
        appBrowseRecord.setRecordType("1");
        return AjaxResult.success(appBrowseRecordService.selectAppBrowseRecordList(appBrowseRecord));
    }

    /**
     * 批量删除浏览记录
     */
    @PreAuthorize("@ss.hasPermi('app:user:browse')")
    @ApiOperation(value = "批量删除浏览记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "浏览记录id（多个用英文逗号隔开）", dataType = "String", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/deleteBrowseList")
    public AjaxResult deleteBrowseList(
            @RequestParam String ids,
            HttpServletRequest request, HttpServletResponse response) {
        if (com.zhengshang.common.utils.StringUtils.isBlank(ids)) {
            return AjaxResult.error("参数错误");
        }
        int row = appBrowseRecordService.deleteAppBrowseRecordByIds(ids.split(","));
        return AjaxResult.success("成功删除" + row + "条浏览记录");
    }

    /**
     * 获取收藏列表
     */
    @PreAuthorize("@ss.hasPermi('app:user:collection')")
    @ApiOperation(value = "获取收藏列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10条，最大100）", required = false, dataType = "int", paramType = "query")
    })
    @GetMapping("/collectionList")
    public AjaxResult collectionList(
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) {
        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        AppBrowseRecord appBrowseRecord = new AppBrowseRecord();
        appBrowseRecord.getParams().put("pageNum", pageNum);
        appBrowseRecord.getParams().put("pageSize", pageSize);
        appBrowseRecord.setUserId(loginAppUser.getAppUser().getUserId());
        appBrowseRecord.setRecordType("2");
        return AjaxResult.success(appBrowseRecordService.selectAppBrowseRecordList(appBrowseRecord));
    }

    /**
     * 批量删除收藏记录
     */
    @PreAuthorize("@ss.hasPermi('app:user:collection')")
    @ApiOperation(value = "批量删除收藏记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "收藏记录id（多个用英文逗号隔开）", dataType = "String", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/deleteCollectionList")
    public AjaxResult deleteCollectionList(
            @RequestParam String ids,
            HttpServletRequest request, HttpServletResponse response) {
        if (com.zhengshang.common.utils.StringUtils.isBlank(ids)) {
            return AjaxResult.error("参数错误");
        }
        int row = appBrowseRecordService.deleteAppBrowseRecordByIds(ids.split(","));
        return AjaxResult.success("成功删除" + row + "条浏览记录");
    }


    @PreAuthorize("@ss.hasPermi('app:user:withdrawal')")
    @ApiOperation(value = "提现申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "money", value = "提现金额", required = true, dataType = "bigDecimal", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "提现类型（1支付宝，2银行卡，3微信）", required = true, dataType = "String", paramType = "query"),
    })
    @RepeatSubmit
    @PostMapping("/withdrawal")
    public AjaxResult withdrawal(
            @RequestParam BigDecimal money,
            @RequestParam String type,
            HttpServletRequest request, HttpServletResponse response) {

        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        String withdrawalCheck = configService.selectConfigByKey("app.withdrawal.check");

        if (StringUtils.isBlank(withdrawalCheck) || !"0".equals(withdrawalCheck)) {
            if (!isWithdrawal()) {
                return AjaxResult.error("当前时段不可提现！");
            }
            if (appCashingRecordService.queryTodayCount(new AppCashingRecord(loginAppUser.getAppUser().getUserId())) > 0) {
                return AjaxResult.error("每天只能提现一次！");
            }
        }
        BigDecimal minMoney = new BigDecimal(configService.selectConfigByKey("app.withdrawal.min"));
        BigDecimal maxMoney = new BigDecimal(configService.selectConfigByKey("app.withdrawal.max"));
        if (money == null || StringUtils.isBlank(type)) {
            return AjaxResult.error("参数错误");
        }
        if (money.compareTo(minMoney) < 0) {
            return AjaxResult.error("单笔最低可提现 " + minMoney.doubleValue() + " 元");
        }
        if (money.compareTo(maxMoney) > 0) {
            return AjaxResult.error("单笔最高可提现 " + maxMoney.doubleValue() + " 元");
        }


        SysUser appUser = userService.selectUserById(loginAppUser.getAppUser().getUserId());
        if (appUser.getAppAccountBalance().compareTo(money) < 0) {
            return AjaxResult.error("账户余额不足！");
        }
        if (StringUtils.isBlank(appUser.getBankCard()) || appUser.getBankId() == null) {
            return AjaxResult.error("请先绑定提现方式！");
        }
        if (AppConstant.APP_WITHDRAWAL_ALIPAY.equals(type) && StringUtils.isBlank(appUser.getAlipay())) {
            return AjaxResult.error("请先绑定支付宝支付！");
        }
        if (AppConstant.APP_WITHDRAWAL_WXPAY.equals(type) && StringUtils.isBlank(appUser.getWxpay())) {
            return AjaxResult.error("请先绑定微信支付！");
        }
        loginAppUser.setAppUser(appUser);
        AppCashingRecord appCashingRecord = new AppCashingRecord();
        if (AppConstant.APP_WITHDRAWAL_ALIPAY.equals(type)) {
            appCashingRecord.setCashingAccount(appUser.getAlipay());
        } else if (AppConstant.APP_WITHDRAWAL_BANKCARD.equals(type)) {
            appCashingRecord.setCashingAccount(appUser.getBankCard());
            appCashingRecord.setBankId(appUser.getBankId());
            appCashingRecord.setBankName(appBankService.selectAppBankNameById(appUser.getBankId()));
        } else if (AppConstant.APP_WITHDRAWAL_WXPAY.equals(type)) {
            appCashingRecord.setCashingAccount(appUser.getWxpay());
        }
        BigDecimal withdrawalFee = new BigDecimal(configService.selectConfigByKey("app.withdrawal.fee"));
        BigDecimal fee = withdrawalFee.divide(new BigDecimal(100));
        BigDecimal cashingPoundage = money.multiply(fee).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal realMoney = money.subtract(cashingPoundage);
        appCashingRecord.setCashingPoundage(cashingPoundage);
        appCashingRecord.setCashingMoney(money);
        appCashingRecord.setCashingType(type);
        appCashingRecord.setCashingFullname(appUser.getRealName());
        appCashingRecord.setRealMoney(realMoney);
        appUser = userService.withdrawal(appUser, appCashingRecord);

        //获取数据库最新数据并更新到redis中
        loginAppUser.setAppUser(appUser);
        tokenService.refreshToken(loginAppUser);
        return AjaxResult.success("提现申请成功");
    }

    @PreAuthorize("@ss.hasPermi('app:user:withdrawal')")
    @ApiOperation(value = "提现列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "state", value = "1提现中，2已提现，3已驳回", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @PostMapping("/withdrawalList")
    public AjaxResult withdrawalList(
            @RequestParam String state,
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response
    ) {
        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1) || StringUtils.isBlank(state)) {
            return AjaxResult.error("参数错误");
        }
        if (!"1".equals(state) && !"2".equals(state) && !"3".equals(state)) {
            return AjaxResult.error("非法参数");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        AppCashingRecord appCashingRecord = new AppCashingRecord();
        appCashingRecord.setCashingState(state);
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        appCashingRecord.setUserId(loginAppUser.getAppUser().getUserId());
        appCashingRecord.getParams().put("pageNum", pageNum);
        appCashingRecord.getParams().put("pageSize", pageSize);
        return AjaxResult.success(appCashingRecordService.selectAppCashingRecordList(appCashingRecord));
    }

    @PreAuthorize("@ss.hasPermi('app:user:activity')")
    @ApiOperation(value = "活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @PostMapping("/activityList")
    public AjaxResult activityList(
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) {
        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        AppActivity appActivity = new AppActivity();
        appActivity.getParams().put("pageNum", pageNum);
        appActivity.getParams().put("pageSize", pageSize);
        appActivity.setStatus("2");
        List<AppActivity> appActivityList = appActivityService.queryList(appActivity);
        for (AppActivity activity : appActivityList) {
            activity.setCoverImgUrl(configService.selectConfigByKey("sys.oss.file.header") + activity.getCoverImgUrl());
        }
        return AjaxResult.success(appActivityList);
    }

    @ApiOperation(value = "生成分享二维码")
    @PostMapping("/createQRCode")
    public AjaxResult createQRCode(
            HttpServletRequest request, HttpServletResponse response) {
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            String url = configService.selectConfigByKey("app.invitation.url") + "?code=" + loginAppUser.getAppUser().getPromoCode();
            String base64 = QRCodeUtils.createQRCode(url);
            logger.info("<createQRCode>生成二维码成功：{}", base64);
            return AjaxResult.success("生成成功", base64);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @PreAuthorize("@ss.hasPermi('app:user:balance')")
    @ApiOperation(value = "余额变动记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @PostMapping("/balanceList")
    public AjaxResult balanceList(
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response
    ) {

        try {
            if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
                return AjaxResult.error("参数错误");
            }
            if (pageSize == null) {
                pageSize = 10;
            }
            if (pageSize.intValue() > 100) {
                pageSize = 100;
            }
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            AppBalanceRecord appBalanceRecord = new AppBalanceRecord();
            appBalanceRecord.setUserId(loginAppUser.getAppUser().getUserId());
            appBalanceRecord.getParams().put("pageNum", pageNum);
            appBalanceRecord.getParams().put("pageSize", pageSize);
            List<AppBalanceRecord> appBalanceRecordList = appBalanceRecordService.selectAppBalanceRecordList(appBalanceRecord);
            Map<String, SysDictData> dictDataMap = dictTypeService.selectDictDataByTypeToMap("app_balance_modify_source");
            if (dictDataMap != null) {
                for (int i = 0; i < appBalanceRecordList.size(); i++) {
                    SysDictData sysDictData = dictDataMap.get(appBalanceRecordList.get(i).getModifySource());
                    appBalanceRecordList.get(i).setModifySource(sysDictData == null ? "" : sysDictData.getDictLabel());
                }
            }
            return AjaxResult.success(appBalanceRecordList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<user.balanceList>获取余额变动记录失败，{}", e.getMessage());
        }
        return AjaxResult.error();
    }

    @ApiOperation(value = "意见反馈")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "opinion", value = "意见", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
    })
    @RepeatSubmit
    @PostMapping("/feedback")
    public AjaxResult feedback(
            @RequestParam String opinion,
            @RequestParam String phone,
            HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(opinion) || StringUtils.isBlank(phone)) {
            return AjaxResult.error("参数错误");
        }
        if (opinion.trim().length() > 1000) {
            return AjaxResult.error("意见最多只能输入1000个字");
        }
        //TODO 数据库存储意见
        logger.info("<user.feedback>[{}]：{}", phone, opinion);
        return AjaxResult.success("您的意见我们已经知道啦，我们的工作人员会尽快给您回复的，给您带来的不便敬请谅解。");
    }

    @ApiOperation(value = "获取合伙人等级规则")
    @PreAuthorize("@ss.hasPermi('app:user:partner')")
    @PostMapping("/getPartnerSection")
    public AjaxResult getPartnerSection(
            HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        String partnerName = configService.selectConfigByKey("app.vip.partner.name");
        jsonObject.put("partnerName", partnerName);
        jsonObject.put("partnerSection", PartnerLevelUtils.getSection());
        return AjaxResult.success("获取成功", jsonObject);
    }

    @ApiOperation(value = "绑定提现方式")
    @PreAuthorize("@ss.hasPermi('app:user:withdrawal')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realName", value = "真实姓名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "bankId", value = "银行ID", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "bankCard", value = "银行卡卡号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "alipay", value = "支付宝", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "wxpay", value = "微信", required = false, dataType = "String", paramType = "query"),
    })
    @RepeatSubmit
    @PostMapping("/bindWithdrawalMode")
    public AjaxResult bindWithdrawalMode(
            @RequestParam String realName,
            @RequestParam Long bankId,
            @RequestParam String bankCard,
            @RequestParam(required = false) String alipay,
            @RequestParam(required = false) String wxpay,
            HttpServletRequest request, HttpServletResponse response) {
        try {

            if (bankId == null || StringUtils.isBlank(realName) || StringUtils.isBlank(bankCard)) {
                return AjaxResult.error("参数错误");
            }
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            loginAppUser.getAppUser().setRealName(realName);
            loginAppUser.getAppUser().setAlipay(alipay);
            loginAppUser.getAppUser().setBankCard(bankCard);
            loginAppUser.getAppUser().setBankId(bankId);
            loginAppUser.getAppUser().setWxpay(wxpay);
            userService.updateAppUser(loginAppUser.getAppUser());
            tokenService.refreshToken(loginAppUser);
            if (StringUtils.isNotBlank(loginAppUser.getAppUser().getAvatar()) && loginAppUser.getAppUser().getAvatar().indexOf("https://") == -1) {
                loginAppUser.getAppUser().setAvatar(configService.selectConfigByKey("sys.oss.file.header") + loginAppUser.getAppUser().getAvatar());
            }
            return AjaxResult.success("绑定成功", loginAppUser.getAppUser());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("绑定失败");
    }

    @ApiOperation(value = "获取银行列表")
    @PreAuthorize("@ss.hasPermi('app:user:withdrawal')")
    @PostMapping("/getBankList")
    public AjaxResult getBankList(
            HttpServletRequest request, HttpServletResponse response) {
        try {
            return AjaxResult.success("获取成功", appBankService.queryAppBankList(new AppBank()));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<user.getBankList>获取银行列表失败，{}", e.getMessage());
        }
        return AjaxResult.error("获取失败");
    }

    /**
     * 判断是否可以提现（当前为周四可以提现）
     */
    private boolean isWithdrawal() {
        Calendar now = Calendar.getInstance();
        int week = now.get(Calendar.DAY_OF_WEEK);
        int hour = now.get(Calendar.HOUR_OF_DAY);
        //周四，09:00:00 ～ 17:59:59
        if (week == 5 && hour >= 9 && hour <= 17) {
            return true;
        }
        return false;
    }

}
